package com.duan.laugh.mp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duan.laugh.common.core.util.R;
import com.duan.laugh.common.event.constants.EventConstant;
import com.duan.laugh.common.security.util.LaughUser;
import com.duan.laugh.common.security.util.UserUtils;
import com.duan.laugh.mp.api.pojo.entity.MpCustomerMsgTemplate;
import com.duan.laugh.mp.api.pojo.entity.MpFansMsg;
import com.duan.laugh.mp.api.pojo.entity.MpFansMsgRes;
import com.duan.laugh.mp.config.WxMpConfiguration;
import com.duan.laugh.mp.mapper.MpFansMsgMapper;
import com.duan.laugh.mp.mapper.MpFansMsgResMapper;
import com.duan.laugh.mp.service.IMpCustomerMsgTemplateService;
import com.duan.laugh.mp.service.IMpFansMsgResService;
import com.duan.laugh.msg.api.pojo.entity.MsgSend;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 微信消息回复业务
 *
 * @author duanjw
 */
@Slf4j
@Service
@AllArgsConstructor
public class IMpFansMsgResServiceImpl extends ServiceImpl<MpFansMsgResMapper, MpFansMsgRes> implements IMpFansMsgResService {
    private final MpFansMsgMapper wxFansMsgMapper;
    @Autowired
    private IMpCustomerMsgTemplateService mpCustomerMsgTemplateService;

    /**
     * 保存并发送回复
     * <p>
     * 1. 根据消息ID 查询消息的所属 公众号信息
     * 2. 构建文本客服消息并发送
     * 3. 完善回复消息并保存
     * 4. 更新微信消息为已回复
     *
     * @param wxFansMsgRes
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveAndSend(MpFansMsgRes wxFansMsgRes) {
        MpFansMsg wxFansMsg = wxFansMsgMapper.selectById(wxFansMsgRes.getFansMsgId());

        String wxAccountAppid = wxFansMsg.getWxAccountAppid();
        WxMpService wxMpService = WxMpConfiguration.getMpServices().get(wxAccountAppid);

        try {
            wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage
                    .TEXT()
                    .toUser(wxFansMsg.getOpenid())
                    .content(wxFansMsgRes.getResContent())
                    .build());
        } catch (WxErrorException e) {
            log.error("发送客服消息失败 ", e);
            return R.failed(e.getError().getErrorMsg());
        }

        LaughUser user = UserUtils.getUser();
        wxFansMsgRes.setUserId(user.getId());
        wxFansMsgRes.setUserName(user.getUsername());
        baseMapper.insert(wxFansMsgRes);

        wxFansMsg.setIsRes("1");
        wxFansMsgMapper.updateById(wxFansMsg);
        return R.ok();
    }

    /**
     * 消息中心给粉丝推送模版消息
     *
     * @param msgSend
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendWxCustomerTemplateMsg(MsgSend msgSend) {
        // 微信公众号服务
        WxMpService wxMpService = WxMpConfiguration.getMpServices().get("wxa50010df48eec30c");
        // 模版
        Long templateId = msgSend.getTemplateId();
        MpCustomerMsgTemplate customerMsgTemplate = mpCustomerMsgTemplateService.getById(templateId);
        // 替换模版内容
        final Map map = new JSONObject(msgSend.getParams()).toBean(Map.class);
        String content = new StringSubstitutor(map).replace(customerMsgTemplate.getContant());

        String openIds = msgSend.getReceiveObjectValue();
        List<String> openIdList = StrUtil.split(openIds, ',', -1);
        for (int i = 0, n = openIdList.size(); i < n; i++) {
            String openId = openIdList.get(i);
            try {
                wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage
                        .TEXT()
                        .toUser(openId)
                        .content(content)
                        .build());
                log.info("给粉丝推送客服模版消息成功：openId:{},内容:{}", openId, content);
                // 存入日志
                baseMapper.insert(new MpFansMsgRes()
                        .setResContent(content)
                        .setDelFlag(EventConstant.ENABLE)
                        .setCreateTime(LocalDateTime.now())
                        .setTenantId(msgSend.getTenantId()));
            } catch (WxErrorException e) {
                log.error("发送客服消息失败 ", e);
//            return R.failed(e.getError().getErrorMsg());
            }
        }
    }
}
